package com.auth.manager.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @version 1.0.0
 * @Date: 2022/4/27 11:09
 * @Author ZhuYouBin
 * @Description 请求、响应工具类
 */
public class ResponseUtil {

    /**
     * 响应结果数据
     * @param response 响应对象
     * @param result 响应结果
     */
    public static void response(HttpServletResponse response, Object result) throws IOException {
        // 设置响应类型
        response.setContentType("application/json;charset=utf-8");
        // 获取输出流,返回数据
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    /**
     * 从请求正文里面获取请求参数
     * @param request 请求对象
     * @return
     */
    public static String getBody(HttpServletRequest request) throws IOException {
        StringBuilder builder = new StringBuilder();
        // 从输入流中获取请求数据
        BufferedReader reader = request.getReader();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    }

}
